package com.eleadmin.gzh.service;

import com.eleadmin.damon.utils.baiduword.service.BdWordService;
import com.eleadmin.common.core.utils.FileServerUtil;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author Damon
 * @create 2020-09-02 9:11
 */
public class UploadMaterial {


    /**
     * 上传临时素材
     */
    public static String uploadMaterial(String path, String type) {
        File file = new File(path);
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
        url = url.replace("ACCESS_TOKEN", GzhToken.getAccessToken())
            .replace("TYPE", type);
        try {
            URL urlObj = new URL(url);;
            //转https链接
            HttpsURLConnection conn = (HttpsURLConnection)urlObj.openConnection();
            //设置链接信息
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            //设置请求头的信息
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "utf-8");
            //数据的边界
            String boundary = "-----" + System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            OutputStream out = conn.getOutputStream();
            InputStream is = new FileInputStream(file);
            //准备数据
            //第一部分:头部信息
            StringBuilder sb = new StringBuilder();
            sb.append("--");
            sb.append(boundary);
            sb.append("\r\n");
            sb.append("Content-Disposition:form-data;name=\"media\";filename=\""+file.getName()+"\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            out.write(sb.toString().getBytes());
            //第二部分:文件内容
            byte[] b = new byte[1024];
            int len;
            while((len=is.read(b))!=-1){
                out.write(b,0, len);
            }
            //第三部分:尾部信息
            String foot = "\r\n--" + boundary + "--\r\n";
            out.write(foot.getBytes());
            out.flush();
            out.close();
            InputStream is2 = conn.getInputStream();
            StringBuilder resp = new StringBuilder();
            b = new byte[1024];
            while((len=is2.read(b)) != -1){
                resp.append(new String(b, 0, len));
            }
            return resp.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 查看临时素材
     * http://localhost/api/nt/file/downMaterial?media_id=LRJG8IIEG1Z7G1amTmZgSWGe1OwG0t_YJpJAzlPh56OoKeri9aOuQyY6MBf3l378
     */
    public static void downMaterial(String MEDIA_ID, HttpServletResponse response) {
        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        url = url.replace("ACCESS_TOKEN", GzhToken.getAccessToken())
                .replace("MEDIA_ID", MEDIA_ID);
        System.out.println(url);
        //第一种 都可以
//        BufferedInputStream bis =null;
//        try {
//            URL urlObj = new URL(url);
//            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
//            connection.setRequestMethod("GET");
//            connection.setRequestProperty("Content-Type", "application/octet-stream");
//            //设置链接信息
//            connection.setDoInput(true);
//            connection.setDoOutput(true);
//            connection.setUseCaches(false);
//            //设置请求头的信息
//            connection.setRequestProperty("Connection", "Keep-Alive");
//            connection.setRequestProperty("Charset", "utf-8");
//            connection.connect();
//
//            InputStream is= connection.getInputStream();
//            bis = new BufferedInputStream(is);
//            FileUploadUtil.setDownloadHeader(response, "material.jpg");
//            FileUploadUtil.output2(bis, response.getOutputStream());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        //第二种 都可以
        try {
            BdWordService bs = new BdWordService();
            File file = bs.getFileByUrl(url, "jpg");
            FileServerUtil.setDownloadHeader(response, file.getName());
            FileServerUtil.output(file, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
